package hw.ats.news.activity.news;

import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.activity.ats.AtsInfoAct;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.util.App;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.audio.AudioPlayerDialogTool;
import com.tattermedia.allthataudio.audio.AudioPlayerManager;
import com.tattermedia.allthataudio.audio.CommonAudioPlayerStatusListener;
import com.tattermedia.allthataudio.audio.IAudioPlayerStatusListener;
import com.tattermedia.allthataudio.misc.DebugFlag;
import com.tattermedia.allthataudio.views.AudioPlayerProgressView;

public class BookmarkAct extends DBAwareActivity implements ImageReceivedCallback {
	private final static String TAG = "BookmarkAct";
	
	private List<News> items = new ArrayList<News>();
	private ListView listView = null;
	private TabHost navbar = null;
	private boolean editMode = false;
	private boolean thumbDisplay = false;
	
	// 페이징
	private int start = 0;
	private int rows = App.ROW_PER_PAGE;
	private boolean hasNext = true;
	
	// audio status listener
	private IAudioPlayerStatusListener mAudioStatusListener;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        thumbDisplay = pref.getBoolean("pref_list_thumb", true);
        
        loadData();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.act_bookmark);
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB3);
		
		// 네이게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonBackEvent(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        ImageButton rightImageButton = (ImageButton)findViewById(R.id.navbar_left);
        if (rightImageButton != null) {
        	rightImageButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(BookmarkAct.this, AtsInfoAct.class);
					BookmarkAct.this.startActivity(intent);
				}
			});
        }
        
        listView = (ListView)findViewById(R.id.bookmark_list);
        listView.setAdapter(new BookmarkAdapter(this));
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				News news = items.get(position);
				Intent intent = new Intent(BookmarkAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, BookmarkAct.class.getName());
			    startActivity(intent);
			}
        });
        
        ImageButton editBookmark = (ImageButton)findViewById(R.id.navbar_right);
        editBookmark.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				editMode = !editMode;
				((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
			}
		});
        
        // add audio status listener
        mAudioStatusListener = new CommonAudioPlayerStatusListener(
        		(ImageButton)findViewById(R.id.audio_player_button_play), 
        		(ImageButton)findViewById(R.id.audio_player_button_repeat),
        		(ImageButton)findViewById(R.id.audio_player_button_prev),
        		(ImageButton)findViewById(R.id.audio_player_button_next),
        		(TextView)findViewById(R.id.audio_player_text_subject),
        		(TextView)findViewById(R.id.audio_player_text_time),
        		(AudioPlayerProgressView)findViewById(R.id.audio_player_progress_view));
        
        AudioPlayerManager.getManager().addAudioPlayerStatusListener(mAudioStatusListener);
        mAudioStatusListener.onAudioStatusChanged(IAudioPlayerStatusListener.TYPE_COMMON);
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		
		AudioPlayerManager.getManager().removeAudioPlayerStatusListener(mAudioStatusListener);
		
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
	@Override
	protected void onRestart() {
		super.onRestart();
		
		((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();	
	}
    
    
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event)  {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//	    	Intent intent = new Intent(BookmarkAct.this, RecmdAct.class);
//	    	startActivity(intent);
//	    	finish();
//	    	overridePendingTransition(0, 0);
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
    
    /**
     * 이미지 로더
     */
	public void onImageReceived(ImageDisplayer displayer) {
		this.runOnUiThread(displayer);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
    private void loadData() {
		hasNext = false;
		List<News> newItems = News.listFavor(getReadableDatabase(), start, rows + 1);
		if (newItems != null && newItems.size() > 0) {
			if (newItems.size() == rows + 1) {
				newItems.remove(rows);
				hasNext = true;
			}
			items.addAll(newItems);
		}
    }
    
	/**
	 * 다음 페이지 데이터 조회
	 */
    private void loadNextData() {
    	start += App.ROW_PER_PAGE;
    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	        		BookmarkAct.this, App.APP_TITLE, "글을 조회하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				loadData();
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}

			@Override
			protected void onPostExecute(Boolean result) {
				((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
				progressDialog.dismiss();
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
    
	private class BookmarkAdapter extends BaseAdapter {
		private final static String TAG = "BookmarkAdapter";
	   	private final Activity context;

        public BookmarkAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
        	int len = items.size();
        	if (len < App.ROW_PER_PAGE) {
        		hasNext = false;
        	}
        	
        	return len + (hasNext ? 1 : 0);
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            BookmarkHolder holder = null;
            
            // 페이징
            if (items.size() == position) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_more_article, null);
            	ImageButton btn = (ImageButton)view.findViewById(R.id.row_more_btn);
            	btn.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				loadNextData();
        			}
        		});
            	return view;
            }
            
            if (view == null || view.getTag() == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	
//            	if (thumbDisplay)
//            		view = vi.inflate(R.layout.row_bookmark_type2, null);
//            	else
            		view = vi.inflate(R.layout.row_bookmark_type1, null);
            	
                holder = new BookmarkHolder(view);
                view.setTag(holder);
            } else {
            	holder = (BookmarkHolder)view.getTag();
            }

            final News entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
            if (DebugFlag.isLogEnabled()) 
            	Log.d(TAG,
            		"pos="+position+
            		" img="+holder.imageView+
            		" cv="+convertView+
            		" par="+parent+
            		" editMode="+editMode);
            
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageResource(App.RES_LOADING_110x75);
                new ImageReceiver(entry.thumb_default, (ImageReceivedCallback)context, 
                		holder.imageView, getThumbPath(), position);
            }
            
            if (entry.body_text == null || entry.body_text.length() == 0) {
	            if (holder.titleView != null)
	            	holder.titleView.setText("");
	            if (holder.titleOnlyView != null)
	            	holder.titleOnlyView.setText(entry.title);
	            if (holder.detailView != null)
	            	holder.detailView.setText("");
            } else {
	            if (holder.titleView != null)
	            	holder.titleView.setText(entry.title);
	            if (holder.titleOnlyView != null)
	            	holder.titleOnlyView.setText("");
	            if (holder.detailView != null) {
	            	int len = entry.body_text.length();
	            	if (len > 256) len = 256;
	            	holder.detailView.setText(entry.body_text.substring(0, len));
	            }
            }
            
            if (holder.imageButton != null) {
        		holder.imageButton.setFocusable(false);
        		holder.imageButtonPlay.setFocusable(false);

            	if (editMode) {
            		holder.imageButton.setVisibility(View.VISIBLE);
            		holder.imageButtonPlay.setVisibility(View.GONE);
            		
                	holder.imageButton.setOnClickListener(new OnClickListener() {
    					@Override
    					public void onClick(View v) {
    						new AlertDialog.Builder(BookmarkAct.this)
    						.setTitle(App.APP_TITLE)
    						.setMessage("글을 북마크 보관함에서 삭제하시겠습니까?")
    						.setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() {
    						    public void onClick(final DialogInterface dialog, final int arg1) {
    						    	entry.markFavorite(getWritableDatabase(), false);
    						    	items.remove(entry);
    						    	((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
    						    }
    						})
    						.setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() {
    						    public void onClick(final DialogInterface dialog, final int arg1) {
    						    }
    						})
    						.show();
    					}
    				});
            		
            	} else {
            		holder.imageButtonPlay.setVisibility(View.VISIBLE);
            		holder.imageButton.setVisibility(View.GONE);
            		
            		holder.imageButtonPlay.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							AudioPlayerDialogTool.showPlayOrAddDialog(BookmarkAct.this, entry);							
						}
					});
            		
                	if (entry.mp3_url.trim().length() == 0) {
                		holder.imageButtonPlay.setEnabled(false);
                	} else {
                		holder.imageButtonPlay.setEnabled(true);
                	}
            		
            	}
            	
            }
            
    		
    		return view;
        }
	}
	
	private class BookmarkHolder {
		public final TextView titleView;
		public final TextView titleOnlyView;
		public final TextView detailView;
		public final ImageView imageView;
		public final ImageButton imageButton;
		public final ImageButton imageButtonPlay;
		
		public BookmarkHolder(View view) {
			titleView = (TextView)view.findViewById(R.id.row_title);
			titleOnlyView = (TextView)view.findViewById(R.id.row_title_only);
			detailView = (TextView)view.findViewById(R.id.row_detail);
			imageView = (ImageView)view.findViewById(R.id.row_photo);
			imageButton = (ImageButton)view.findViewById(R.id.row_delete_btn);
			imageButtonPlay = (ImageButton)view.findViewById(R.id.row_button_play);

		}
	}
}
